<template>
  <div class="app-container configurationData">
    <search-form :search-data="formInline" :search-form="searchData">
      <slot>
        <el-tooltip
          class="item"
          effect="dark"
          content="点击可前进"
          placement="right"
        >
          <el-button type="primary" icon="el-icon-back" @click="handleGOback" />
        </el-tooltip>
        <el-tooltip
          class="item"
          effect="dark"
          content="点击可后退"
          placement="right"
        >
          <el-button
            type="primary"
            icon="el-icon-right"
            @click="handleGONextback"
          />
        </el-tooltip>
      </slot>
    </search-form>
    <div class="configuration-main">
      <div id="myDiagramDiv" ref="container-Bg"></div>
    </div>

    <!-- 指令下发弹框 -->
    <el-dialog
      :title="'指令下发' + '(' + form.title + ')'"
      v-model="dialogFormVisible"
      width="30%"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="设定数值" v-if="form.dataType === 'text'">
          <el-input
            v-model="form.value"
            oninput="value=value.replace(/[^0-9.-]/g,'')"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="设定数值" v-if="form.dataType === 'list'">
          <el-select v-model="form.value" filterable placeholder="请选择">
            <el-option
              v-for="item in enumsOptions"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="saveSetDataFn">确 定</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import searchForm from "@/components/SearchForm/index.vue";
import gojsConfig from "./index";
import store from "@/store/index";
// import { getHeatSourcePermisstion } from "@/api/heatSource";
import { getHeatStation } from "@/api/heatStation";
import { getSystemList } from "@/api/system";
import { getConfiguration, getConfigurationContent } from "@/api/configuration";
import timer from "@/utils/setTime";
import { realOneSend } from "@/api/realDataManage";
export default {
  name: "configurationData",
  components: { searchForm },
  data() {
    return {
      gridVisible: false,
      formInline: {
        heatSourceId: "",
        heatStationId: "",
        heatSystemId: "",
        chartId: "",
      },
      addForm: {
        backgroundColor: null,
        alarmColor: "#FF0000",
        alarmDataColor: "#FF0000",
        onlineDataColor: "#666",
        normalDataColor: "#333",
      },
      searchData: [
        {
          type: "Select",
          prop: "heatSourceId",
          options: [],
          placeholder: "选择热源",
          change: (row) => {
            this.handleHeatSourceChange(row);
          },
        },
        {
          type: "Select",
          prop: "heatStationId",
          options: [],
          placeholder: "选择换热站",
          change: () => {
            this.handleHeatStationChange();
          },
        },
        {
          type: "Select",
          prop: "heatSystemId",
          options: [],
          placeholder: "选择系统",
          change: () => {
            this.getConfigurationList();
          },
        },
        {
          type: "Select",
          prop: "chartId",
          options: [],
          placeholder: "选择组态",
          change: () => {
            this.getConfigurationChart();
          },
        },
      ],
      historyPagesN: [],
      historyIdx: 0,
      dialogFormVisible: false,
      form: {
        id: "",
        title: "",
        name: "",
        dataType: "",
        value: 0,
      },
      enumsOptions: [], //枚举
    };
  },
  mounted() {
    this.getHeatSourceList();
    gojsConfig.setVm(this);
    gojsConfig.GOJSInit("myDiagramDiv");
  },
  beforeUnmount() {
    timer.ctbi("reData");
    timer.ctbi("gojs.loopLink");
    timer.ctbi("gojs.loopNode");
  },
  methods: {
    getHeatSourceList() {
      this.searchData[0].options = store.getters.sourceData;
    },
    /**
     * 根据热源查询换热站和系统
     *
     */
    handleHeatSourceChange(val) {
      this.getHeatStationList(val);
      this.getSystemData();
      this.getConfigurationList();
    },
    /**
     * 根据换热站查询系统
     */
    handleHeatStationChange() {
      this.getSystemData();
      this.getConfigurationList();
    },
    /**
     * 获取组态列表
     */
    getConfigurationList() {
      const { heatSourceId, heatStationId, heatSystemId } = this.formInline;
      let param = { heatSourceId, heatStationId, heatSystemId };

      this.formInline.chartId = "";
      this.searchData[3].options = [];

      if (heatSourceId == "") {
        this.formInline.chartId = "";
        this.searchData[3].options = [];
        return;
      }
      getConfiguration(param).then((res) => {
        if (res.data.success) {
          let { data } = res.data;
          const result = data.map((item) => {
            return { label: item.name, value: item.id, ...item };
          });
          this.searchData[3].options = result;
        }
      });
    },
    /**
     * 获取换热站列表
     */
    async getHeatStationList(id) {
      this.formInline.heatStationId = "";
      this.searchData[1].options = [];
      if (id == "" || id == null || id == undefined) {
        this.formInline.heatStationId = "";
        this.searchData[1].options = [];
        return;
      }

      const { data: resp } = await getHeatStation({ heatSourceId: id });
      if (resp.success) {
        const listResult = resp.data.map((item) => {
          return { label: item.name, value: item.id };
        });
        this.searchData[1].options = listResult;
      }
    },
    /**
     * 获取系统列表
     */
    getSystemData() {
      this.formInline.heatSystemId = "";
      this.searchData[2].options = [];
      const { heatStationId, heatSourceId } = this.formInline;

      let params = { heatSourceId, heatStationId };

      getSystemList(params).then((res) => {
        if (res.data.success) {
          const { data } = res.data;
          const list =
            data &&
            data.map((item) => {
              return { label: item.name, value: item.id };
            });
          this.searchData[2].options = list;
        }
      });
    },
    /**
     * 加载组态图
     */
    getConfigurationChart() {
      const { chartId } = this.formInline;

      if (chartId == "") {
        gojsConfig.GOSJLoad({}, true);
        return;
      }
      getConfigurationContent({ id: chartId }).then((res) => {
        if (res.data.success) {
          const {
            content,
            alarmColor,
            alarmDataColor,
            normalDataColor,
            onlineDataColor,
            backgroundColor,
          } = res.data.data[0];
          gojsConfig.GOSJLoad(content, true);

          this.$refs["container-Bg"].style.backgroundColor = backgroundColor;
          this.addForm.backgroundColor = backgroundColor;
          this.addForm.alarmColor = alarmColor;
          this.addForm.alarmDataColor = alarmDataColor;
          this.addForm.normalDataColor = normalDataColor;
          this.addForm.onlineDataColor = onlineDataColor;
        }
      });
    },
    /**查询组态列表和内容 */
    initBackData(SourceId, StationId, SystemId, chartId) {
      const { heatSourceId, heatStationId, heatSystemId } = this.formInline;
      getConfiguration({ heatSourceId, heatStationId, heatSystemId }).then(
        (res) => {
          if (res.data.success) {
            let { data } = res.data;
            const result = data.map((item) => {
              return { label: item.name, value: item.id };
            });
            this.searchData[3].options = result;

            this.formInline.heatSourceId = SourceId;
            this.formInline.heatStationId = StationId;
            this.formInline.heatSystemId = SystemId;
            this.formInline.chartId = chartId;

            getConfigurationContent({ id: chartId }).then((response) => {
              if (response.data.success) {
                const {
                  content,
                  alarmColor,
                  alarmDataColor,
                  normalDataColor,
                  onlineDataColor,
                  backgroundColor,
                } = response.data.data[0];
                gojsConfig.GOSJLoad(content, true);

                this.$refs[
                  "container-Bg"
                ].style.backgroundColor = backgroundColor;
                this.addForm.alarmColor = alarmColor;
                this.addForm.alarmDataColor = alarmDataColor;
                this.addForm.normalDataColor = normalDataColor;
                this.addForm.onlineDataColor = onlineDataColor;
              }
            });
          }
        }
      );
    },
    handleGOback() {
      if (this.historyIdx == 0) return false;
      this.historyIdx--;
      const obj1 = this.historyPagesN[this.historyIdx];
      if (obj1 == undefined) return false;
      this.historyPagesN[this.historyIdx] = obj1;

      this.initBackData(
        obj1.heatSourceId,
        obj1.heatStationId,
        obj1.heatSystemId,
        obj1.chartId
      );
    },
    handleGONextback() {
      if (this.historyIdx == this.historyPagesN.length - 1) return false;
      this.historyIdx++;
      const obj = this.historyPagesN[this.historyIdx];
      if (obj == undefined) return false;
      this.historyPagesN[this.historyIdx] = obj;
      this.initBackData(
        obj.heatSourceId,
        obj.heatStationId,
        obj.heatSystemId,
        obj.chartId
      );
    },
    /** 点击文本跳转刷新页面 */
    async goBackPage(data) {
      const { heatSourceId, heatStationId, heatSystemId, pathId } = data;
      if (heatSourceId && pathId) {
        const currentObj = {
          heatSourceId: this.formInline.heatSourceId,
          heatStationId: this.formInline.heatStationId,
          heatSystemId: this.formInline.heatSystemId,
          chartId: this.formInline.chartId,
        };
        const dataObj = {
          // 点id
          heatSourceId: heatSourceId,
          heatStationId: heatStationId,
          heatSystemId: heatSystemId,
          chartId: pathId,
        };

        if (this.historyPagesN.length == 0) {
          this.historyPagesN = [currentObj, dataObj];
          this.historyIdx++;
        } else {
          if (this.historyIdx === this.historyPagesN.length - 1) {
            this.historyPagesN.push(dataObj);
            this.historyIdx++;
          } else {
            this.historyIdx++;
            this.historyPagesN.splice(this.historyIdx, 0, dataObj);
            this.historyPagesN.slice(0, this.historyIdx);
          }
        }

        this.initBackData(heatSourceId, heatStationId, heatSystemId, pathId);
      }
    },
    /**
     * 数据下发
     */
    saveSetDataFn() {
      let params = { id: this.form.id, value: this.form.value };

      realOneSend(params).then((res) => {
        if (res.data.success) {
          this.$message.success("下发成功，请耐心等待一个周期才可以查看");
          this.dialogFormVisible = false;
        }
      });
    },
  },
};
</script>
<style lang="less" scoped>
.configurationData {
  width: 100%;
  height: 100%;
  .configuration-main {
    height: calc(100% - 60px);
    display: flex;
    flex-direction: row;
    border: 1px solid #ccc;

    #myDiagramDiv {
      flex: 1;
      height: 100%;
      // background: #f8f8f8;
      // border: 1px solid #ccc;
      margin-left: 10px;
    }
  }
}
</style>
